<template>
  <main class="main fx">
    <textarea class="raw" :value="val" @input="handleInp" v-if="!fullEditor">
    </textarea>
    <div class="wrap" v-else>
      <textarea class="raw" ref="text" :value="val" @input="handleInp">
      </textarea>
    </div>
    <div class="real" v-html="article_html"></div>
  </main>
</template>

<script>
import marked from "marked";
const rendererMD = new marked.Renderer();
marked.setOptions({
  renderer: rendererMD,
  gfm: true,
  tables: true,
  breaks: true,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,

  highlight: function (code) {
    return hljs.highlightAuto(code).value;
  },
});
export default {
  name: "ArticleMain",
  data() {
    return {
      val: "",
      fullEditor: false,
    };
  },
  methods: {
    handleInp(e) {
      this.val = e.target.value;
      this.$bus.$emit("articleChange", this.val);
    },
    setUpFull() {
      const textarea = this.$refs.text;
      const editor = new Editor({
        element: textarea,
      });
      editor.render(textarea);
      editor.codemirror.getValue();
      editor.codemirror.on("change", (v) => {
        this.val = v.getValue();
        // 触发得到内容
        this.$bus.$emit("articleChange", this.val);
      });
    },
  },
  computed: {
    article_html() {
      const val = marked(this.val);
      this.$bus.$emit("articleHtmlChange", val);
      return val;
    },
  },
  created() {
    // 发布文章成功要置空
    this.$bus.$on("resetToEmpty", () => {
      this.val = "";
    });
    // 登录后重新获取该值
    this.$bus.$on("articleFull", (val) => {
      this.val = val;
    });
    // this.$bus.$on("changeEditor", (type) => {
    //   console.log(type);
    //   this.fullEditor = type;
    //   type && this.setUpFull();
    // });
  },
  mounted() {
    if (this.fullEditor) {
      this.setUpFull();
    }
  },
};
</script>

<style lang="scss">
.main {
  height: calc(100% - 6.4rem);
  .raw {
    overflow: auto;
    width: 50%;
    border-right: 1px solid #eaeaea;
    line-height: 1.5;
  }
  .wrap {
    width: 50%;
    border-right: 1px solid #eaeaea;
  }
  .real {
    width: 50%;
    overflow: auto;
    line-height: 1.2;
    h1,
    h2,
    h3,
    h4 {
      font-weight: bold;
    }
    ul {
      list-style-type: initial;
      line-height: 1.5;
      margin-left: 4rem;
    }
    ol {
      list-style: decimal;
    }
  }
  .real,
  .raw {
    padding: 2rem;
  }
}
</style>